# classIfication
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
from joblib import dump

from sklearn.preprocessing import  LabelEncoder
from sklearn.svm import SVC

class ClassIfication(object): 
    def __init__(self):
        self.df = pd.read_csv('daily.csv')
    
    def get_conditions(self):
            """分类前准备"""

            #计算收益和风险比例
            df = self.df
            df['max_ratio'] = df['max_close'] / df['the_close'] #收益潜力
            df['min_ratio'] = df['min_close'] / df['the_close'] #风险程度

            #自动划分高低阈值
            high_return_threshold = df['max_ratio'].quantile(0.4)#钱40%定义为高收入
            high_risk_threshold = df['min_ratio'].quantile(0.4)#钱40%定义为高风险

            #生成分类标签
            conditions = [
                (df['max_ratio'] >= high_return_threshold) & (df['min_ratio'] >=high_risk_threshold),
                (df['max_ratio'] <= high_return_threshold) & (df['min_ratio'] >=high_risk_threshold),
                (df['max_ratio'] < high_return_threshold) & (df['min_ratio'] >=high_risk_threshold),
                (df['max_ratio'] < high_return_threshold) & (df['min_ratio'] >=high_risk_threshold),
            ]
            labels = ['高收益风险', '高收益低风险', '低收益低风险', '低收益高风险']
            df['catrgory'] = np.select(conditions, labels,default= ' 未知')

        
        #标签编码
            from sklearn.preprocessing import LabelEncoder
            le = LabelEncoder
            df['catrgory_encoded'] = le.fit_transform(df['category'])
            #标签选择
            features = df([
            'esp','total_revenue_ps', 'undist_profit_ps', 'gross_margin', 'fcff', 'fcfe', 'tangible_asset', 'bps', 'grossprofit_margin','npta' 
        ])
    
        #数据标准化
            scaler = StandardScaler()
            X = scaler.fit_transform(features)
            Y = df['catrgory_encoded']

        #划分训练集和测试集
            X_train, X_test, Y_train, Y_test = train_test_split(x,Y,test_size=0.3, random_state=24)
            dump(scaler,'feature_scaler.joblib')
            return  X_train, X_test, Y_train, Y_test, le

    def  knn_utils(self, X_test,X_train,Y_test,Y_train, le):
        """knn模型训练方法"""
        knn = KNeighborsClassifier(n_neighbors=3)
        knn.fit(X_train,Y_train)

        #预测与评估
        Y_pred = knn.predict(X_test)

        print(classification_report(Y_test, Y_pred, target_names=le.classes_))

        #保存模型
        dump(knn, 'knn_classifien.joblib')
        dump(le, 'label_endoder.joblie')

    def svc_utils(self, X_test,X_train,Y_train, Y_test, le):
        """支持向量机模型训练方法"""
        svc = SVC()
        svc.fit(X_train, Y_train)
        predict = svc.predict(X_test)
        print("accuracy_score: %.4lf" : % accuracy_score(predict, y_test))
        print("Classification report for classifier %s: \n %s \n" % (svc, classification_report(Y_test, predict)))
            
        
if __name__ == '__main__':
    ci = ClassIfication()
    X_train, X_test, Y_train, Y_test, le  = ci.get_conditions()
    #ci.knn_utils( X_train, X_test, Y_train, Y_test, le)
    ci.svc_utils( X_train, X_test, Y_train, Y_test)       